package org.aaron.demos;

import java.lang.reflect.Type;
import java.util.LinkedList;

import org.aaron.demos.model.User;

import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class GsonActivity extends ListActivity {

	private String jsonStr = "[{\"username\":\"aaron\",\"password\":\"123\"},{\"username\":\"fiona\",\"password\":\"456\"}]";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gsonlayout);
		initActivity();
	}

	private void initActivity() {
		Button button = (Button) findViewById(R.id.GsonBtn);
		button.setOnClickListener(new ButtonOnClickListener());

	}

	class ButtonOnClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			Gson gson = new Gson();
			Type typeToken = new TypeToken<LinkedList<User>>() {
			}.getType();
			LinkedList<User> linkedList = gson.fromJson(jsonStr, typeToken);
			for (User user : linkedList) {
				Log.d("UserName", user.getUsername());
				Log.d("PassWord", user.getPassword());
			}
		}

	}
}
